import logging

from celery.signals import (
    after_setup_logger,
    after_setup_task_logger,
    task_failure,
    task_success,
)
from redis import Redis

try:
    from app import create_app
except ImportError:
    celery_app = None
else:
    _ = create_app()
    from tools import celery_app  # noqa


logger = logging.getLogger(__name__)


@after_setup_logger.connect
def setup_loggers(logger, *args, **kwargs):
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )

    # FileHandler
    fh = logging.FileHandler("celery_logs.log")
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    # SysLogHandler
    # slh = logging.handlers.SysLogHandler(address=('logsN.test_app.com', '...'))
    # slh.setFormatter(formatter)
    # logger.addHandler(slh)


@after_setup_task_logger.connect
def setup_task_logger(logger, **kwargs):
    logger.propagate = 1


@task_success.connect
def clean_dump_request_context_on_success(sender=None, result=None, **kwargs):
    """在任务成功清理任务初始化时转储的请求上下文"""
    redis: Redis = sender.app.flask_app.extensions["redis"]
    redis.delete(f"TASK_DUMP_REQUEST_CONTEXT::{sender.request.id}")


@task_failure.connect
def clean_dump_request_context_on_failure(sender=None, result=None, **kwargs):
    """在任务失败后清理任务初始化时转储的请求上下文"""

    redis: Redis = sender.app.flask_app.extensions["redis"]
    redis.delete(f"TASK_DUMP_REQUEST_CONTEXT::{sender.request.id}")
